KindEditor.lang({
  'uploadimg': '添加图片',
  'uploadimg.remoteImage': '网络图片',
  'uploadimg.localImage': '本地上传',
  'uploadimg.remoteUrl': '图片地址',
  'uploadimg.localUrl': '上传文件',
  'uploadimg.size': '图片大小',
  'uploadimg.width': '宽',
  'uploadimg.height': '高',
  'uploadimg.resetSize': '重置大小',
  'uploadimg.align': '对齐方式',
  'uploadimg.defaultAlign': '默认方式',
  'uploadimg.leftAlign': '左对齐',
  'uploadimg.rightAlign': '右对齐',
  'uploadimg.imgTitle': '图片说明',
  'uploadimg.upload': '浏览...',
});
KindEditor.plugin('uploadimg', function (K) {
  var self = this
  var name = 'uploadimg'
  var uploadimgUrl = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php')
  var extraParams = K.undef(self.extraFileUploadParams, {})
  var filePostName = K.undef(self.filePostName, 'file')
  var formatUploadUrl = K.undef(self.formatUploadUrl, true)
  var fillDescAfterUploadImage = K.undef(self.fillDescAfterUploadImage, false)
  var lang = self.lang(name + '.')
  var allowImageUpload = K.undef(self.allowImageUpload, true)
  var allowImageRemote = K.undef(self.allowImageRemote, true)
  var imageTabIndex = K.undef(self.imageTabIndex, 0)
  var staticHost = K.undef(self.staticHost, null)
  // console.log(lang)
  // 点击图标时执行
  self.plugin.uploadImgDialog = function (options) {
    var imgPath = self.pluginsPath + 'image/images/'
    var clickFn = options.clickFn;
    var imageUrl = options.imageUrl
    var imageHeight = options.imageHeight
    var imageWidth = options.imageWidth
    var imageTitle = options.imageTitle
    var imageAlign = options.imageAlign
    var tabIndex = options.tabIndex
    var select = options.select

    var target = 'kindeditor_upload_iframe_' + new Date().getTime();
    var html = [
      '<div style="padding:20px;">',
      //local upload - start
      '<div class="tab2" >',

      '<iframe name="' + target + '" style="display:none;"></iframe>',
      '<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + K.addParam(uploadimgUrl, 'dir=image') + '">',
      //file
      '<div class="ke-dialog-row">',
      //   hiddenElements.join(''),
      '<label style="width:60px;">' + lang.localUrl + '</label>',

      '<input type="text" id="textcontainer" name="localUrl" class="ke-input-text" tabindex="-1" style="width:200px;" value="' + imageUrl + '" readonly="true" /> &nbsp;',
      '<input type="button" id="imp-upload-btn" class="ke-upload-button" value="' + lang.upload + '" />',
      '</div>',
      '<input type="file" id="filecontainer" name="file" style="visibility:hidden"/>',
      '</form>',
      '<div class="ke-dialog-row">',
      '<label for="remoteWidth" style="width:60px;">' + lang.size + '</label>',
      lang.width + ' <input type="text" id="remoteWidth" class="ke-input-text ke-input-number" name="width" value="' + imageWidth + '" maxlength="4" /> ',
      lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="' + imageHeight + '" maxlength="4" /> ',
      '<img class="ke-refresh-btn" src="' + imgPath + 'refresh.png" width="16" height="16" alt="" style="cursor:pointer;" title="' + lang.resetSize + '" />',
      '</div>',
      //align
      '<div class="ke-dialog-row">',
      '<label style="width:60px;">' + lang.align + '</label>',
      '<input type="radio" name="align" class="ke-inline-block" value="" checked="checked" /> <img name="defaultImg" src="' + imgPath + 'align_top.gif" width="23" height="25" alt="" />',
      ' <input type="radio" name="align" class="ke-inline-block" value="left" /> <img name="leftImg" src="' + imgPath + 'align_left.gif" width="23" height="25" alt="" />',
      ' <input type="radio" name="align" class="ke-inline-block" value="right" /> <img name="rightImg" src="' + imgPath + 'align_right.gif" width="23" height="25" alt="" />',
      '</div>',
      //title
      '<div class="ke-dialog-row">',
      '<label for="remoteTitle" style="width:60px;">' + lang.imgTitle + '</label>',
      '<input type="text" id="remoteTitle" class="ke-input-text" name="title" value="" style="width:200px;" />',
      '</div>',
      '</div>',
      //local upload - end
      '</div>'
    ].join('');
    var dialog = self.createDialog({
      name: name,
      width: 450,
      title: self.lang(name),
      body: html,
      yesBtn: {
        name: self.lang('yes'),
        click: function (e) {
          if (!select) {
            var fileObj = filecontainer.files[0]; // 获取文件对象
            var FileController = uploadimgUrl; // 接收上传文件的后台地址 
            if (extraParams && extraParams.token) {
              FileController += '?token='+extraParams.token
              //   console.log(uploadimgUrl)
              // FormData 对象
              var form = new FormData();

              form.append(filePostName, fileObj); // 文件对象
              // for (var key in extraParams) {
              //   form.append(key, extraParams[key])
              // }
              // console.log(form.get("token"))
              // console.log(form.get("file"))
              // console.log(form)
              // XMLHttpRequest 对象
              var xhr = new XMLHttpRequest();
              xhr.open("post", FileController, true);
              xhr.onreadystatechange = function (response) {
                if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
                  var data = JSON.parse(xhr.response);
                  if (data.code === 0) {
                    var url = data.jdata;
                    url = staticHost + url
                    urlBox.val(url)
                    if (dialog.isLoading) {
                      return;
                    }
                    // insert remote image
                    var
                      width = widthBox.val(),
                      height = heightBox.val(),
                      title = titleBox.val(),
                      align = '';
                    setTimeout(function () {
                      clickFn.call(self, url, title, width, height, 0, align);
                    }, 1000);
                    // clickFn.call(self, url, title, width, height, 0, align);
                  } else {
                    alert(data.message);
                  }
                }
              }
              //   xhr.onload = function (response) {
              //     console.log(response)
              //     alert("上传完成!");
              //   };
              xhr.send(form);
            }
            
          } else {
            var url = select.attr('data-ke-src'),
              width = widthBox.val(),
              height = heightBox.val(),
              title = titleBox.val(),
              align = '';
            clickFn.call(self, url, title, width, height, 0, align);
          }
        }
      }
    })
    var div = dialog.div;
    var urlBox = K('[name="url"]', div),
      widthBox = K('.tab2 [name="width"]', div),
      heightBox = K('.tab2 [name="height"]', div),
      titleBox = K('.tab2 [name="title"]', div),
      alignBox = K('.tab2 [name="align"]', div);

    var textcontainer = document.getElementById('textcontainer')
    var filecontainer = document.getElementById('filecontainer')
    filecontainer.addEventListener('change', function (e) {
      // console.log(textcontainer)
      textcontainer.value = filecontainer.value
    })
    document.getElementById('imp-upload-btn').addEventListener('click', function (e) {
      filecontainer.click()
    })
  };

  self.plugin.image = {
    edit: function () {
      var img = self.plugin.getSelectedImage();

      self.plugin.uploadImgDialog({
        select: img,
        imageUrl: img ? img.attr('data-ke-src') : 'http://',
        imageWidth: img ? img.width() : '',
        imageHeight: img ? img.height() : '',
        imageTitle: img ? img.attr('title') : '',
        imageAlign: img ? img.attr('align') : '',
        tabIndex: img ? 0 : imageTabIndex,
        clickFn: function (url, title, width, height, border, align) {
          if (img) {
            img.attr('src', url);
            img.attr('data-ke-src', url);
            img.attr('width', width);
            img.attr('height', height);
            img.attr('title', title);
            img.attr('align', align);
            img.attr('alt', title);
          } else {
            setTimeout(function () {
              self.exec('insertimage', url, title, width, height, border, align);
            }, 1000);
           
          }

          setTimeout(function () {
            self.hideDialog().focus();
          }, 0);
        }
      })
    },
    delete: function () {
      var target = self.plugin.getSelectedImage();
      if (target.parent().name == 'a') {
        target = target.parent();
      }
      target.remove();
      // [IE] 删除图片后立即点击图片按钮出错
      self.addBookmark();
    }
  }
  self.clickToolbar(name, self.plugin.image.edit);
});
